"use strict";
var coreModule = require('../core_module');
var lodash_1 = require('lodash');
var $ = require('jquery');
require('vendor/jquery.ajaxfileupload');

coreModule.directive('settingView', function() {
  return {
    restrict: 'A',
    template: require('../../partials/window-manager-setting.html')
  }
});

function laygroup(adata, col, len) {
  var dataLen = adata.length;
  var rowData = [];
  len = len || dataLen;
  for (var i = 0; i < len / col; i++) {
    var row = [];
    for (var j = 0; j < col; j++) {
      if (i * col + j < dataLen)
        row.push(adata[i * col + j]);
      else
        break;
    }
    rowData.push(row);
  }
  return rowData;
}

coreModule.controller('LoadWindowManagerCtrl', function($scope, loadReactModuleSrv, $rootScope, backendSrv, $location) {

  $scope.layout = {
    width: '30',
    height: '30'
  };

  $scope.windows = [];
  $scope.windowlists = [];
  $scope.col = 1;

  $scope.$watch('windowlists', function() {
    $scope.windowlists.push({
      uri: 'new',
      className: 'window-add-new',
      title: 'new'
    });

    if ($scope.windowlists && $scope.windowlists.length > 0) {
      var len = $scope.windowlists.length;

      switch (len) {
        case 1:
          $scope.windows = laygroup($scope.windowlists, $scope.col, len);
          break;
        case 2:
        case 3:
        case 4:
          $scope.col = 2;
          $scope.windows = laygroup($scope.windowlists, $scope.col, len);
          break;
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          $scope.col = 3;
          $scope.windows = laygroup($scope.windowlists, $scope.col, len);
          break;
        case 10:
        default:
          $scope.col = 4;
          $scope.windows = laygroup($scope.windowlists, $scope.col, len);
          $scope.layout.width = '22';
          break;
      }
    }
  })

  $scope.openEditView = function() {
    $scope.setting = true;
    $location.search('setting');
  };

  $scope.fullScreen = function() {
    $scope.appEvent('full-screen');
  }

  $scope.saveEditView = function() {
    backendSrv.post('/api/windowmanager/setting/save', {
      title: $scope.title,
      bg: $scope.image
    }).then(function(data) {
      $scope.dismiss();
    });
  };

  $scope.dismiss = function() {
    $scope.setting = false;
    $location.search('');
  }

  $scope.editWindow = function(window) {
    loadReactModuleSrv.create(require('../reactmodules/modal/modal.jsx'), $scope);
  }

  function ajaxFileUpload() {
    $.ajaxFileUpload({
      url: '/api/upload/pic', //用于文件上传的服务器端请求地址
      secureuri: false, //一般设置为false
      fileElementId: 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
      dataType: 'json', //返回值类型 一般设置为json
      success: function(data, status) {
        if (data.errCode != 200)
          $rootScope.appEvent('alert-error', ['', data.message]);
        else {
          $scope.image = data.data;
          $rootScope.appEvent('alert-success', ['', '图片上传成功']);
        }

      },
      error: function(data, status, e) {
        $rootScope.appEvent('alert-error', ['', e]);
      }
    })
    return false;
  }

  function getFileSize(elem) {
    var byteSize = 0;
    if (elem.files) {
      var byteSize = elem.files[0].size;
    } else {

    }
    byteSize = Math.ceil(byteSize / 1024) //KB
    return byteSize; //KB
  }

  $scope.fileNameChanged = function(elem) {
    var allowImgageType = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
    var $file = $(elem)
    var file = $file.val();
    //获取大小
    var byteSize = getFileSize($file[0]);
    //获取后缀
    if (file.length > 0) {
      if (byteSize > 2048) {
        $rootScope.appEvent('alert-error', ['', "上传的附件文件不能超过2M"]);
        return;
      }
      var pos = file.lastIndexOf(".");
      //截取点之后的字符串
      var ext = file.substring(pos + 1).toLowerCase();
      //console.log(ext);
      if ($.inArray(ext, allowImgageType) != -1) {
        ajaxFileUpload();
      } else {
        $rootScope.appEvent('alert-error', ['', "请选择jpg,jpeg,png,gif类型的图片"]);
      }
    } else {
      $rootScope.appEvent('alert-error', ['', "请选择jpg,jpeg,png,gif类型的图片"]);
    }
  }

  backendSrv.request({
    url: '/api/windowmanager/setting/get'
  }).then(function(data) {
    $scope.title = data.title;
    $scope.image = data.bg;

    if (!$rootScope.userInfo)
      $rootScope.userInfo = window.USER_INFO;
  });

  backendSrv.search().then(function(data) {
    $scope.windowlists = data;
  });

  if ($location.search().setting === true) {
    $scope.setting = true;
  }
});



coreModule.controller('DashFromImportCtrl', function($scope, $location, alertSrv) {
  if (!window.grafanaImportDashboard) {
    alertSrv.set('Not found', 'Cannot reload page with unsaved imported dashboard', 'warning', 7000);
    $location.path('');
    return;
  }
  $scope.initDashboard({
    meta: { canShare: false, canStar: false },
    dashboard: window.grafanaImportDashboard
  }, $scope);
});

coreModule.controller('NewDashboardCtrl', function($scope) {
  $scope.initDashboard({
    meta: { canStar: false, canShare: false },
    dashboard: {
      title: "New dashboard",
      rows: [{ height: '250px', panels: [] }]
    },
  }, $scope);
});
